<template>
  <view class="settings-container">
    <view class="header">
      <text class="title">家庭设置</text>
    </view>
    
    <view class="settings-list">
      <view class="setting-item" @click="editFamilyInfo">
        <text class="setting-icon">✏️</text>
        <text class="setting-text">编辑家庭信息</text>
        <text class="setting-arrow">></text>
      </view>
      
      <view class="setting-item" @click="manageMember">
        <text class="setting-icon">👥</text>
        <text class="setting-text">成员管理</text>
        <text class="setting-arrow">></text>
      </view>
      
      <view class="setting-item" @click="inviteMember">
        <text class="setting-icon">➕</text>
        <text class="setting-text">邀请成员</text>
        <text class="setting-arrow">></text>
      </view>
      
      <view class="setting-item" @click="familyPrivacy">
        <text class="setting-icon">🔒</text>
        <text class="setting-text">隐私设置</text>
        <text class="setting-arrow">></text>
      </view>
      
      <view class="setting-item danger" @click="handleLeaveFamily">
        <text class="setting-icon">🚪</text>
        <text class="setting-text">退出家庭</text>
        <text class="setting-arrow">></text>
      </view>
    </view>
    
    <!-- 编辑家庭信息模态框 -->
    <view class="modal-overlay" v-if="showEditModal" @click="closeEditModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑家庭信息</text>
          <text class="close-btn" @click="closeEditModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="label">家庭名称</text>
            <input 
              class="input" 
              v-model="editForm.name" 
              placeholder="请输入家庭名称"
              maxlength="50"
            />
          </view>
          <view class="form-item">
            <text class="label">家庭描述</text>
            <textarea 
              class="textarea" 
              v-model="editForm.description" 
              placeholder="请输入家庭描述（可选）"
              maxlength="200"
            />
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn btn-secondary" @click="closeEditModal">取消</button>
          <button class="btn btn-primary" @click="saveFamily" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 邀请成员模态框 -->
    <view class="modal-overlay" v-if="showInviteModal" @click="closeInviteModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">邀请成员</text>
          <text class="close-btn" @click="closeInviteModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="invite-section">
            <text class="section-title">邀请码</text>
            <view class="invite-code-container">
              <text class="invite-code">{{ familyInfo?.inviteCode || 'LOADING...' }}</text>
              <button class="copy-btn" @click="copyInviteCode">复制</button>
            </view>
            <text class="invite-desc">分享此邀请码给家人，他们可以通过此码加入家庭</text>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn btn-primary" @click="closeInviteModal">关闭</button>
        </view>
      </view>
    </view>
    
    <!-- 隐私设置模态框 -->
    <view class="modal-overlay" v-if="showPrivacyModal" @click="closePrivacyModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">隐私设置</text>
          <text class="close-btn" @click="closePrivacyModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="privacy-item">
            <view class="privacy-info">
              <text class="privacy-title">公开家庭</text>
              <text class="privacy-desc">允许其他用户搜索到你的家庭</text>
            </view>
            <switch :checked="privacySettings.isPublic" @change="onPublicChange" />
          </view>
          <view class="privacy-item">
            <view class="privacy-info">
              <text class="privacy-title">允许搜索</text>
              <text class="privacy-desc">允许通过家庭名称被搜索</text>
            </view>
            <switch :checked="privacySettings.allowSearch" @change="onSearchChange" />
          </view>
          <view class="privacy-item">
            <view class="privacy-info">
              <text class="privacy-title">需要审批</text>
              <text class="privacy-desc">新成员加入需要管理员审批</text>
            </view>
            <switch :checked="privacySettings.requireApproval" @change="onApprovalChange" />
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn btn-secondary" @click="closePrivacyModal">取消</button>
          <button class="btn btn-primary" @click="savePrivacySettings" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  name: 'FamilySettings',
  
  data() {
    return {
      showEditModal: false,
      showInviteModal: false,
      showPrivacyModal: false,
      
      // 编辑家庭信息表单
      editForm: {
        name: '',
        description: ''
      },
      
      // 隐私设置
      privacySettings: {
        isPublic: true,
        allowSearch: true,
        requireApproval: false
      },
      
      loading: false
    }
  },
  
  computed: {
    ...mapState('family', ['familyInfo']),
    ...mapState('user', ['userInfo'])
  },
  
  onLoad() {
    this.loadFamilyInfo()
  },
  
  methods: {
    ...mapActions('family', ['getFamilyInfo', 'updateFamilyInfo', 'generateInviteCode', 'leaveFamily', 'updatePrivacySettings']),
    
    // 加载家庭信息
    async loadFamilyInfo() {
      try {
        await this.getFamilyInfo()
        if (this.familyInfo) {
          this.editForm.name = this.familyInfo.name || ''
          this.editForm.description = this.familyInfo.description || ''
          
          // 初始化隐私设置
          this.privacySettings.isPublic = this.familyInfo.isPublic !== 0
          this.privacySettings.allowSearch = this.familyInfo.allowSearch !== 0
          this.privacySettings.requireApproval = this.familyInfo.requireApproval === 1
        }
      } catch (error) {
        console.error('加载家庭信息失败:', error)
      }
    },
    
    // 编辑家庭信息
    editFamilyInfo() {
      if (this.familyInfo) {
        this.editForm.name = this.familyInfo.name || ''
        this.editForm.description = this.familyInfo.description || ''
      }
      this.showEditModal = true
    },
    
    manageMember() {
      uni.navigateTo({
        url: '/pages/family/members'
      })
    },
    
    // 关闭编辑模态框
    closeEditModal() {
      this.showEditModal = false
    },
    
    // 保存家庭信息
    async saveFamily() {
      if (!this.editForm.name.trim()) {
        uni.showToast({
          title: '请输入家庭名称',
          icon: 'none'
        })
        return
      }
      
      this.loading = true
      try {
        await this.updateFamilyInfo({
          name: this.editForm.name.trim(),
          description: this.editForm.description.trim()
        })
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        this.closeEditModal()
        await this.loadFamilyInfo() // 重新加载数据
        
      } catch (error) {
        console.error('保存家庭信息失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 邀请成员
    inviteMember() {
      this.showInviteModal = true
    },
    
    // 关闭邀请模态框
    closeInviteModal() {
      this.showInviteModal = false
    },
    
    // 复制邀请码
    copyInviteCode() {
      const inviteCode = this.familyInfo?.inviteCode
      if (!inviteCode) {
        uni.showToast({
          title: '邀请码获取中',
          icon: 'none'
        })
        return
      }
      
      uni.setClipboardData({
        data: inviteCode,
        success: () => {
          uni.showToast({
            title: '邀请码已复制',
            icon: 'success'
          })
        }
      })
    },
    
    // 刷新邀请码
    async refreshInviteCode() {
      try {
        await this.generateInviteCode()
        uni.showToast({
          title: '邀请码已刷新',
          icon: 'success'
        })
      } catch (error) {
        console.error('刷新邀请码失败:', error)
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        })
      }
    },
    
    // 隐私设置
    familyPrivacy() {
      this.showPrivacyModal = true
    },
    
    // 关闭隐私模态框
    closePrivacyModal() {
      this.showPrivacyModal = false
    },
    
    // 隐私设置变更处理
    onPublicChange(e) {
      this.privacySettings.isPublic = e.detail.value
    },
    
    onSearchChange(e) {
      this.privacySettings.allowSearch = e.detail.value
    },
    
    onApprovalChange(e) {
      this.privacySettings.requireApproval = e.detail.value
    },
    
    // 保存隐私设置
    async savePrivacySettings() {
      this.loading = true
      try {
        await this.updatePrivacySettings(this.privacySettings)
        
        uni.showToast({
          title: '隐私设置保存成功',
          icon: 'success'
        })
        this.closePrivacyModal()
      } catch (error) {
        console.error('保存隐私设置失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 退出家庭
    async handleLeaveFamily() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出当前家庭吗？退出后将无法查看家庭内容，需要重新加入。',
        confirmColor: '#ff4757',
        success: async (res) => {
          if (res.confirm) {
            try {
              await this.leaveFamily()
              
              uni.showToast({
                title: '已退出家庭',
                icon: 'success'
              })
              
              // 跳转到创建/加入家庭页面
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/family/create-simple'
                })
              }, 1500)
              
            } catch (error) {
              console.error('退出家庭失败:', error)
              uni.showToast({
                title: error.message || '退出失败',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.settings-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40rpx;
}

.header {
  margin-bottom: 40rpx;
  
  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: #333;
  }
}

.settings-list {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  
  .setting-item {
    display: flex;
    align-items: center;
    padding: 40rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.danger {
      .setting-text {
        color: #ff4757;
      }
    }
    
    .setting-icon {
      font-size: 40rpx;
      margin-right: 24rpx;
    }
    
    .setting-text {
      flex: 1;
      font-size: 32rpx;
      color: #333;
    }
    
    .setting-arrow {
      font-size: 32rpx;
      color: #ccc;
    }
  }
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 20rpx;
  width: 85%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  
  .modal-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 36rpx;
    color: #666;
    padding: 10rpx;
  }
}

.modal-body {
  padding: 30rpx;
}

.modal-footer {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  border-top: 1rpx solid #f5f5f5;
  
  .btn {
    flex: 1;
    text-align: center;
    padding: 24rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    border: none;
    
    &.btn-primary {
      background-color: #007AFF;
      color: white;
      
      &:disabled {
        opacity: 0.6;
      }
    }
    
    &.btn-secondary {
      background-color: #f5f5f5;
      color: #333;
    }
  }
}

// 表单样式
.form-item {
  margin-bottom: 30rpx;
  
  .label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 12rpx;
    font-weight: 500;
  }
  
  .input, .textarea {
    width: 100%;
    border: 1rpx solid #e0e0e0;
    border-radius: 12rpx;
    padding: 20rpx;
    font-size: 28rpx;
    background-color: #fafafa;
    
    &:focus {
      border-color: #007AFF;
      background-color: white;
    }
  }
  
  .textarea {
    min-height: 120rpx;
    resize: none;
  }
}

// 邀请相关样式
.invite-section {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    display: block;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.invite-code-container {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  
  .invite-code {
    flex: 1;
    font-size: 32rpx;
    font-weight: bold;
    color: #007AFF;
    font-family: 'Courier New', monospace;
  }
  
  .copy-btn {
    background-color: #007AFF;
    color: white;
    border: none;
    border-radius: 8rpx;
    padding: 12rpx 24rpx;
    font-size: 24rpx;
  }
}

.invite-desc {
  font-size: 24rpx;
  color: #666;
  line-height: 1.6;
}

// 隐私设置样式
.privacy-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  .privacy-info {
    flex: 1;
    
    .privacy-title {
      display: block;
      font-size: 30rpx;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .privacy-desc {
      font-size: 24rpx;
      color: #666;
      line-height: 1.4;
    }
  }
}
</style> 